package main

import (
	"bytes"
	"github.com/gin-gonic/gin"
	"io/ioutil"
	"net/http"
	"time"
)

func main() {
	r := gin.Default()
	//type group [2]rune
	//var entity2 map[string]group
	//entity2= make(map[string]group)
	//entity2["s"]=[2]rune{'a','b'}
	//GET
	r.GET("/hello/:name", func(c *gin.Context) {
		c.JSON(200, gin.H{
			"message": "hello " + c.Param("name") + "!get",
		})
	})
	//GET 带参数
	r.GET("/test", func(c *gin.Context) {
		// #go时间格式化 https://blog.csdn.net/permike/article/details/73548247
		now := time.Now().Format(time.RFC3339)
		//DefaultQuery获取查询参数，带默认值
		c.String(http.StatusOK, "hello,%s %s", c.DefaultQuery("name", "none"), now)
	})
	//POST
	//curl -X POST "http://127.0.0.1:8080/post" -d "first_name=lucy&last_name=michael"
	r.POST("/post", func(c *gin.Context) {
		bodyBytes, err := ioutil.ReadAll(c.Request.Body)
		if err != nil {
			c.String(http.StatusBadRequest, "发生错误：%s", err.Error())
			c.Abort()
		}
		//io util只能读一次，将bodyBytes重新封装一下
		//读取curl -X POST "http://127.0.0.1:8080/post" -d "a=x&b=y"
		c.Request.Body = ioutil.NopCloser(bytes.NewBuffer(bodyBytes))
		firstName := c.PostForm("first_name")
		lastName := c.DefaultPostForm("last_name", "-")
		//c.JSON(200,gin.H{
		//	"message":"hello!post",
		//	"reqJson":string(bodyBytes),
		//})
		c.String(200, "your name : %s %s ,%s", firstName, lastName, string(bodyBytes))
	})
	//DELETE
	r.Handle("DELETE", "/delete", func(c *gin.Context) {
		c.JSON(200, gin.H{
			"message": "hello!delete",
		})
	})
	//any method
	r.Any("/any", func(c *gin.Context) {
		c.JSON(200, gin.H{
			"message": "hello!any",
		})
	})

	_ = r.Run() //port：8080
}
